package cn.edu.swpu.cins.u_chain.utils;

import cn.edu.swpu.cins.u_chain.Exception.user.UserException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;

@Service
public class UploadFile {
    @Value("${u_chain.image.location}")
    private String imageLocation;
    @Value("${u_chain.PRD.location}")
    private String PRDLocation;
    @Value("${u_chain.video.location}")
    private String videoLocation;
    @Value("${u_chain.printScreen.location}")
    private String printScreenLocation;


    public String upload(MultipartFile multipartFile, int id,String status) throws IOException {
        String path;
        String str = String.valueOf(new Date().getTime());
        String type=multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."))
                .toLowerCase();
        String fileName;
        switch (status) {
            case "PRD":
                path = PRDLocation;
                fileName = id + "_" + str + "_PRD"  + type;
                break;
            case "image":
                path = imageLocation;
                fileName = id + "_" + str + "_image"  + type;
                break;
            case "video":
                path = videoLocation;
                fileName = id + "_"  + type;
                break;
            case "printScreen":
                //这里可能会创建目录了
                path = checkDir(id);
                fileName = id + "_" + str + "_" + type;
                break;
            default:
                throw new UserException("上传失败");

        }
        path += "/" + fileName;
        File file = new File(path);
        multipartFile.transferTo(file);
        return path;
    }

    private String checkDir(int worksId) throws FileNotFoundException {
        String path = printScreenLocation + "/" + worksId;
        File dir = new File(path);
        if (!dir.exists()) {
            if (!dir.mkdirs()) {
                throw new FileNotFoundException("create dir failed");
            }
        }
        return path;
    }
}
